'use strict';
var React = require('react');
var ReButton=require('./ReButton.jsx');

class ReFileUpload extends React.Component {
    constructor(props) {
        super(props);
        this.selectFile=this.selectFile.bind(this);
        this.onChange=this.onChange.bind(this);
    }

    selectFile(){
        this.refs.fileInput.click();
    }
    onChange(event) {
        event.preventDefault();
        var target = event.target;
        var files = target.files;
        var count = this.props.multiple ? files.length : 1;
        var i;
        for (i = 0; i < count; i++) {
            files[i].thumb = URL.createObjectURL(files[i])
        }
        // convert to array
        files = Array.prototype.slice.call(files, 0);
        files = files.filter(function (file) {
            return /image/i.test(file.type)
        });
        this.props.onChange(files, event)
    }

    render() {
        var className = this.props.className;
        return (
            <div className="ReFileUpload">
                <input className="ReFileUpload_Real" type="file" multiple={this.props.multiple} ref="fileInput" onChange={this.onChange}/>
                <ReButton reButtonClick={this.selectFile}>{this.props.btnValue}</ReButton>
            </div>
        )
    }

}


ReFileUpload.defaultProps = {
    multiple: true,
    btnValue: 'Upload Image',
    className: 'upload-button'
};

ReFileUpload.propTypes = {
    onChange: React.PropTypes.func.isRequired,
    multiple: React.PropTypes.bool,
    btnValue: React.PropTypes.string
};

module.exports = ReFileUpload;